<?php
class ModelStockStockIn extends Model {
 	public function getList($page = 1, $filter){
		$polist = M('stock_in')
		->join('left join user v on v.user_id=stock_in.user_id')
		->join('left join warehouse w on w.warehouse_id=stock_in.warehouse_id')
		->join('left join refer_type r on r.refer_type_id=stock_in.refer_type_id')
		->join('left join inout_state i on i.id=stock_in.status')
		->order('stock_in.date_added DESC')
		->where($filter)
		->field('stock_in.*,v.username, w.name as warehouse_name ,r.name as refer_type,i.name as status_name')
		->page($page)->limit($this->config->get('config_limit_admin'))->select();
		   // echo M('stock_in')->getlastsql();
		return $polist;
	}
	public function getAllList($filter){
		$polist = M('stock_in')
		->join('left join user v on v.user_id=stock_in.user_id')
		->join('left join warehouse w on w.warehouse_id=stock_in.warehouse_id')
		->join('left join refer_type r on r.refer_type_id=stock_in.refer_type_id')
		->join('left join inout_state i on i.id=stock_in.status')
		->order('stock_in.in_id DESC')
		->where($filter)
		->field('stock_in.*,v.username, w.name as warehouse_name ,r.name as refer_type,i.name as status_name')
		->select();
		   // echo M('stock_in')->getlastsql();
		return $polist;
	}


	public function getListCount($filter){
		$count = M('stock_in')
		->join('left join user v on v.user_id=stock_in.user_id')
		->join('left join warehouse w on w.warehouse_id=stock_in.warehouse_id')
		->join('left join refer_type r on r.refer_type_id=stock_in.refer_type_id')
		->join('left join inout_state i on i.id=stock_in.status') 
		->where($filter)
		->select();
		// echo M('stock_in')->getlastsql();

		return $count;
	}

	public function getstock($stock_id){
		$polist =M('stock_in')
		->join('left join user v on v.user_id=stock_in.user_id')
		->join('left join warehouse w on w.warehouse_id=stock_in.warehouse_id')
		->join('left join refer_type r on r.refer_type_id=stock_in.refer_type_id')
		->join('left join inout_state i on i.id=stock_in.status')
		->where(array('in_id' => $stock_id ))
		->field('stock_in.*,v.username, w.name as warehouse_name ,r.name as refer_type,w.warehouse_id,i.name as status_name')
		->find();
		$where =' in_id='.$polist['in_id'].' and op.option_value_id=pov.option_value_id' ;
		$polist['product']=M('stock_in_detail')
		->join('left join product_option_value pov on pov.product_code=stock_in_detail.product_code')
		->join('left join product pro on pro.product_id=pov.product_id')
		->join('left join product_description pd on pd.product_id=pov.product_id')
		// ->join('left join inventory i on (pov.product_code=i.product_code and i.warehouse_id='.$polist['warehouse_id'].')')
		->join('left join  option_value_description op on op.option_id=pov.option_id')
		->distinct('pov.product_code')
		->field('stock_in_detail.*,pd.name,pd.product_id,pov.product_code,op.name as oname,pro.sku')
		 ->where($where)
		// ->group('pov.product_code')
		->select();
		// echo M('stock_in_detail') ->getlastsql();
		return $polist;
	}

	public function getWarehouse(){
		$warehouse = M('warehouse')->field('warehouse_id,name')->where('( status=1 )')
		->select();
		return $warehouse;
	}

	public function searchPo($bill){
		$where['po_id'] = $bill;
		$products = M('po_product')
					->join('left join po p on p.id=po_product.po_id')
					->join('left join warehouse w on w.warehouse_id=p.warehouse_id')
					->field('po_product.*,w.name as warehouse_name ')
					->where($where)->select();
		return $products;
	}

	public function searchSo($bill){
		$where['po_id'] = $bill;
		$products = M('ro_product')->where($where)->select();
		return $products;
	}

	public function addstock($data){
		$stockin = M('stock_in');
	  	$datan = array('refer_id'=>$data['refer_id'], 
	  		'refer_type_id'=>$data['refer_type'],
	  		 'warehouse_id'=>$data['warehouse'], 
	  		'user_id'=>$_SESSION['default']['user_id'], 
	  		'buy_money'=>0, 
	  		'status'=>$data['status'], 
	  		'comment'=>$data['comment'], 
	  		'date_added'=>date('Y-m-d H:i:s'),
	  		'in_date'=>date('Y-m-d H:i:s'));
	  		$stockid = $stockin->data($datan)->add();
	  		$total=0;
	  	foreach ($data['products'] as $key => $value) {
	  		$stockind = M('stock_in_detail');
		  	$datad = array('in_id'=>$stockid, 
		  		'product_code'=>$value['product_code'],
		  		 'product_quantity'=>$value['product_quantity'], 
		  		 'product_price'=>$value['product_price'], 
		  		 'products_money'=>$value['product_price']*$value['product_quantity'], 
				'date_added'=>date('Y-m-d H:i:s'));
		  	$total =$total+ $value['product_price']*$value['product_quantity'];
		  	$stockind->data($datad)->add();

	  	}
		$stockin->where(array('in_id'=>$stockid))->data(array('buy_money'=>$total))->save();
		return 	$stockid;
	}

	public function editstock($data){
		// var_dump($data);
		$stockind = M('stock_in_detail');
		$stockP = $stockind->where(array('in_id'=>$data['in_id']))->select();
		$comment = '修改入库单</br>编辑前：</br>';
		foreach ($stockP as $key => $value) {
			$comment .= '编码'.$value['product_code'].'数量'.$value['product_quantity'].'</br>';
		}
		$stockind->where(array('in_id'=>$data['in_id']))->delete();
	  	$total=0;
		$comment .= '编辑后：</br>';
	  	foreach ($data['products'] as $key => $value) {

			$comment .= '编码'.$value['product_code'].'数量'.$value['product_quantity'].'</br>';
	  		
		  	$datad = array('in_id'=>$data['in_id'], 
		  		'product_code'=>$value['product_code'],
		  		 'product_quantity'=>$value['product_quantity'], 
		  		 'product_price'=>$value['product_price'], 
		  		 'products_money'=>$value['product_price']*$value['product_quantity'], 
				'date_added'=>date('Y-m-d H:i:s'));
		  	$total =$total+ $value['product_price']*$value['product_quantity'];
		  	$stockind->data($datad)->add();

	  	}
		M('stock_in')->where(array('in_id'=>$data['in_id']))->data(array('buy_money'=>$total))->save();	
		return $comment;
	}


	  public function getStatusById($data){

  		$status = M('stock_in')->where(array('in_id'=>$data['in_id']))->getField('status');
  		// echo  M('stock_in')->getlastsql();
  		return $status;
  		
	}
  	

  	public function savestock($data){

  		$status = M('stock_in')->where(array('in_id'=>$data['in_id']))->getField('status');
  		if ($status ==1) {
  			$stockind = M('stock_in_detail');
			$olddata = $stockind->where(array('in_id'=>$data['in_id']))->field('product_code,product_quantity')->select();

			$stockind->where(array('in_id'=>$data['in_id']))->delete();
		  	$total=0;
			$comment2 .= '编辑后：</br>';
		  	foreach ($data['products'] as $key => $value) {
				$comment2 .= '编码'.$value['product_code'].'数量'.$value['product_quantity'].'</br>';
			  	$datad = array('in_id'=>$data['in_id'], 
			  		'product_code'=>$value['product_code'],
			  		 'product_quantity'=>$value['product_quantity'], 
			  		 'product_price'=>$value['product_price'], 
			  		 'products_money'=>$value['product_price']*$value['product_quantity'], 
					'date_added'=>date('Y-m-d H:i:s'));
			  	$total =$total+ $value['product_price']*$value['product_quantity'];
			  	$stockind->data($datad)->add();

		  	}
		  	// var_dump($comment2);
			$newdata = $stockind->where(array('in_id'=>$data['in_id']))->field('product_code,product_quantity')->select();
			$flog = (serialize($olddata) == serialize($newdata) ? false : true );
			if ($flog) {
				$comment = '修改入库单</br>编辑前：</br>';

				foreach ($olddata as $key => $value) {
					$comment .= '编码'.$value['product_code'].'数量'.$value['product_quantity'].'</br>';
					
				}
				$comment .= $comment2 ;

			}
			// var_dump($comment);
			M('stock_in')->where(array('in_id'=>$data['in_id']))->data(array('buy_money'=>$total,
				'status'=>2,
				'in_date'=>date('Y-m-d H:i:s')
				))->save();
			return $comment;
  		}else{
  			return;
  		}
  		
	}

  	public function cancel($in_id){
		return M('stock_in')->where(array('in_id'=>$in_id))->data(array('status'=>0))->save();
	}

	public function recover($in_id){
		return M('stock_in')->where(array('in_id'=>$in_id))->data(array('status'=>1))->save();
	}

	public function referType(){
					
		$refer_type = M('refer_type')->field('refer_type_id,name')->select();
		return $refer_type;
	}

	public function getstatus(){
					
		$refer_type = M('inout_state')->select();
		return $refer_type;
	}

	public function getproduct($data){
		$sql = "SELECT pd.name,pov.product_code FROM " . DB_PREFIX . "product_option_value pov LEFT JOIN product_description pd ON pov.product_id = pd.product_id WHERE 1 AND pd.name LIKE '%".$data['filter_name']."%' OR pov.product_code LIKE '%".$data['filter_name']."%' ";
		$query = $this->db->query($sql);
		return $query->rows;
	}



    //入库单完成时，修改后台库存
	public function addInventory($warehouse_id,$data,$refer_type_id, $in_id=0){
		foreach ($data['products'] as $key => $value) {
			$productNum = M('inventory')
			->field('id,available_quantity,product_code,account_quantity,qty_in_onway')
			->where(array('product_code' => $value['product_code'],'warehouse_id'=>$warehouse_id))
			->find();
			if (empty($productNum)) {
				$data = array(
					'warehouse_id'=>$warehouse_id, 
		  			'product_code'=>$value['product_code'],
		  		 	'available_quantity'=>$value['product_quantity'], 
		  		 	'account_quantity'=>$value['product_quantity'], 
					'date_added'=>date('Y-m-d H:i:s'));
			  	$inventoryPK = M('inventory')->data($data)->add();
			}else{
				$total=(int)$productNum['available_quantity']+(int)$value['product_quantity'];
				$totalc=(int)$productNum['account_quantity']+(int)$value['product_quantity'];
				M('inventory')-> where(array('product_code' => $value['product_code'],'warehouse_id'=>$warehouse_id))->data(array('available_quantity'=>$total,'account_quantity'=>$totalc,'date_modified'=>date('Y-m-d H:i:s')))->save();
				//处理采购单的在途库存
				if ($refer_type_id==2) {
					$totalo=max(0, (int)$productNum['qty_in_onway']-(int)$value['product_quantity']);
					M('inventory')-> where(array('product_code' => $value['product_code'],'warehouse_id'=>$warehouse_id))->data(array('qty_in_onway'=>$totalo,'date_modified'=>date('Y-m-d H:i:s')))->save();
				}
				//如果是清仓商品，入的是正常仓，修改前台库存

				$procode = substr($value['product_code'], 0, 10);
				$clearance=M('product')->where(array('product_code'=>$procode))->getField('clearance');
				$type=M('warehouse')->where(array('warehouse_id'=>$warehouse_id))->getField('type');
				// var_dump($clearance);
				// var_dump($type);
				if ($clearance==1&&$type!=3) {
					$quantity = M('product_option_value')->where(array('product_code'=>$value['product_code']))->getField('quantity');
					$quantity+=(int)$value['product_quantity'];
					M('product_option_value')->where(array('product_code'=>$value['product_code']))->save(array('quantity'=>$quantity));
					// echo 111;die();
					
				}
                $inventoryPK = $productNum['id'];
			}

            /*
             * 入库单修改库存后保存库存变更日志
             * @author sonicsjh
             */
            if (0 != (int)$value['product_quantity']){
                $inventoryHistoryData = array(
                    'inventory_id'  => $inventoryPK,//inventory表PK
                    'product_code'  => $value['product_code'],//商品编码（冗余字段）
                    'warehouse_id'  => $warehouse_id,//仓库编号（冗余字段）
                    'account_qty'   => (int)$value['product_quantity'],//财务数量变更（正+ 负-）
                    'available_qty' => (int)$value['product_quantity'],//可用数量变更（正+ 负-）
                    'comment'       => '入库单：'.$in_id.' 完成入库。',//备注（入库单完成、损益单完成、出库单生成、出库单修改、出库单作废）
                    'user_id'       => $this->user->getId(),//操作人PK
                    'date_added'    => date('Y-m-d H:i:s'),//条目创建时间
                );
                M('inventory_history')->data($inventoryHistoryData)->add();
            }

            //更改缺货状态。
            $pcode10 = substr($value['product_code'],0,10);
            M('product')->where(array('product_code' => $pcode10))->data(array('lack_status'=>1,'lack_reason'=>''))->save();

           	if ($refer_type_id==2) {
           		 M('product')->where(array('product_code' => $pcode10))->data(array('status'=>1))->save();
				
			}
			// echo M('product')->getlastsql();
			$this->addInventoryfront($value['product_code'],$value['product_quantity']);
		}
	}
	

	public function getstockHistory($stock_id){
		return M('stock_in_history')->where(array('in_id'=>$stock_id))->select();
		
	}

	public function addStHistory($in_id, $user_id,$comments){
		$username = M('user')->where(array('user_id'=>$user_id))->getField('username');
		$data = array(
					'in_id'=>$in_id, 
		  			'user_id'=>$user_id,
		  			'operator_name'=>$username,
		  		 	'comment'=>$comments, 
					'date_added'=>date('Y-m-d H:i:s'));
		M('stock_in_history')->data($data)->add();
	}

	public function getMomessage($in_id){
		$where['in_id'] = $in_id;
		$res = M('stock_in')
					->join('left join po p on p.id=stock_in.refer_id')
					->join('left join vendors w on w.user_id=p.vendor_id')
					->field('stock_in.in_id,w.company,w.user_id,p.id,stock_in.buy_money,p.total')
					->where($where)->find();
		// echo    M('stock_in')->getlastsql();
		return $res;
	}
	
	public function addMoneyOutP($res) {
		$data = array(
					'refer_total'=>$res['total'], 
					'payables'=>$res['buy_money'], 
		  			'refer_id'=>$res['id'],
		  		 	'refer_type_id'=>2, 
		  		 	'payee'=>$res['company'], 
		  		 	'payee_id'=>$res['user_id'], 
		  		 	'status'=>1, 
					'trader_type'=>1,
					'stock_in_ids'=>$res['in_id'], 
					'date_added'=>date('Y-m-d H:i:s'));
		M('money_out')->data($data)->add();
	}

	public function getMomessageRo($in_id){
		$where['in_id'] = $in_id;
		$res = M('stock_in')
					->join('left join `ro` on `ro`.id=stock_in.refer_id')
					->join('left join customer w on w.customer_id=`ro`.market')
					->field('stock_in.in_id,w.company_name,w.telephone,w.customer_id,`ro`.id,stock_in.buy_money')
					->where($where)->find();
					// echo M('stock_in')->getlastsql();
		return $res;
	}

	public function addMoneyOutRo($res) {
		$data = array(
					'refer_total'=>$res['buy_money'], 
					'payables'=>$res['buy_money'], 
		  			'refer_id'=>$res['id'],
		  		 	'refer_type_id'=>3, 
		  		 	'payee'=>$res['company_name'].'('.$res['telephone'].')', 
		  		 	'payee_id'=>$res['customer_id'], 
		  		 	'status'=>1, 
		  		 	'in_id'=>$res['in_id'], 
					'trader_type'=>2,
					'date_added'=>date('Y-m-d H:i:s'));
		M('money_out')->data($data)->add();
	}

	
	public function getStockM($in_id) {
		$where['in_id'] = $in_id;
		$res = M('stock_in')
					->where($where)->find();
		return $res;
	}
	

	public function getMoney($refer_id) {
		$where = 'refer_id='  .$refer_id.' and refer_type_id=2 and status=1';
		$res = M('money_out') ->where($where)->find();
		return $res;
	}

	
	public function editMoney($money_in,$stockm,$in_id){
		$where = 'money_out_id='  .$money_in['money_out_id'];
		$payables = (int)$money_in['payables']+$stockm['buy_money'];
		$ids = $money_in['stock_in_ids'].','.$in_id;
		$data = array(
					'payables'=>$payables, 
					'date_modified'=>date('Y-m-d H:i:s'),
					'stock_in_ids'=>$ids
					);
		M('money_out')->data($data)->where($where)->save();
	}

	public function addMoHistory($money_out_id, $user_id,$comments){
		$username = M('user')->where(array('user_id'=>$user_id))->getField('username');
		$data = array(
					'money_out_id'=>$money_out_id, 
		  			'user_id'=>$user_id,
		  			'operator_name'=>$username,
		  		 	'comment'=>$comments, 
					'date_added'=>date('Y-m-d H:i:s'));
		M('money_out_history')->data($data)->add();
	}

	//增加前台库存并更改商品状态到待审核
	public function addInventoryfront($product_code,$product_quantity){

		$sql = "SELECT product_id FROM `".DB_PREFIX."product_option_value` WHERE product_code = '".$product_code."'";

		$query_product = $this->db->query($sql);

		$product_id = $query_product->row['product_id'];

		$sql = "UPDATE `".DB_PREFIX."product_option_value` SET quantity = quantity + ".intval($product_quantity)." WHERE product_id = '".$product_id."'";

		$this->db->query($sql);

		$sql = "UPDATE `".DB_PREFIX."product` SET quantity = quantity + ".intval($product_quantity)." WHERE product_id = '".$product_id."'";

		$this->db->query($sql);

		$sql = "UPDATE `".DB_PREFIX."product` SET status = 5 WHERE product_id = '".$product_id."' AND status != 1";

		$this->db->query($sql);

	}

	public function getAllDetaill($filter){
		$polist = M('stock_in')
		->join('left join user v on v.user_id=stock_in.user_id')
		->join('left join warehouse w on w.warehouse_id=stock_in.warehouse_id')
		->join('left join refer_type r on r.refer_type_id=stock_in.refer_type_id')
		->join('left join inout_state i on i.id=stock_in.status')
		->join('left join `stock_in_detail` sid on sid.in_id=stock_in.in_id')
		->join('left join product_option_value pov on pov.product_code=sid.product_code')
		->join('left join product_description pd on pov.product_id=pd.product_id')
		->join('left join product p on pov.product_id=p.product_id')
		->join('left join vendor ve on ve.vproduct_id=p.product_id')
		->join('left join vendors vs on ve.vendor=vs.vendor_id')
		->order('stock_in.in_id DESC')
		->where($filter)
		->field('stock_in.*,v.username, w.name as warehouse_name ,r.name as refer_type,i.name as status_name,pd.name as pname,sid.*,vs.vendor_name,p.ean')
		->select();
		   // echo M('stock_in')->getlastsql();
		return $polist;
	}

	public function getAgvBuyp()
    {

        $sql = "SELECT product.product_code,product.product_class1, vendor.product_cost,product.product_type FROM product LEFT JOIN vendor ON product.product_id = vendor.vproduct_id ";
        // echo $sql;
        $query = $this->db->query($sql);
        foreach ($query->rows as $row) {
            $pCode = substr($row['product_code'], 0, 10);
            if (!empty($pCode)) {
                $ret[$pCode]['product_cost']= max(0, $row['product_cost']);
                $ret[$pCode]['product_class1']=  $row['product_class1'];
                $ret[$pCode]['product_type']=  $row['product_type'];
                
            }
    
        }
        return $ret;
    } 
}
?>